import json

from django.http import JsonResponse, HttpResponse, request

SUCCESS = 1
WRONG_METHOD = 2
WRONG_POINTER = 3
WRONG_PARAM = 4
NOT_LOGIN = 5
NO_ACCESS = 6


def format_response(tag, data=''):
    """
    返回含有状态码的JsonReponse对象
    :param tag: 标签
    :param data: 数据
    :return:JsonReponse实例
    """
    if tag == SUCCESS:
        # return JsonResponse({
        #     "code": 200,
        #     "data": data,
        # })
        if not data:
            if type(data) == list:
                data = []
            elif type(data) == float:
                data = 0
            elif type(data) == int:
                data = 0
            else:
                data = "success"
        result = {
            "code": 200,
            "data": data
        }
        return HttpResponse(json.dumps(result), content_type="application/json,charset=utf-8")
    elif tag == WRONG_METHOD:
        return JsonResponse({
            "code": 500,
            "data": "wrong method"
        })
    elif tag == WRONG_POINTER:
        return JsonResponse({
            "code": 501,
            "data": "don't exist"
        })
    elif tag == WRONG_PARAM:
        return JsonResponse({
            "code": 502,
            "data": "wrong param"
        })
    elif tag == NOT_LOGIN:
        return JsonResponse({
            "code": 503,
            "data": "not login"
        })
    elif tag == NO_ACCESS:
        return JsonResponse({
            "code": 504,
            "data": "no access"
        })


def format_param(req: request, *kwargs):
    """
    解析请求参数
    :param request: application/json 请求数据
    :param kwargs: 参数key
    :return: 对应值的元组 没有则为空
    """
    data = json.loads(req.body.decode())
    result = ()
    for item in kwargs:
        if item in data.keys():
            result += (data[item],)
        else:
            result += ('',)
    return result



